const liLei = {
  name: 'lilei',
  age: 28,
  habits: ['coding', 'hiking', 'running'],
}

// 1. JSON.stringify()
// const liLeiCopy = JSON.parse(JSON.stringify(liLei))
// liLei.habits.splice(2, 1)
// console.log(liLei, liLeiCopy)

// 2. 递归
function deepClone(obj) {
  // 基本类型
  if (typeof obj !== 'object' || obj === null) {
    return obj
  }

  let copy // 拷贝结果

  // 利用原型链判断obj是否是数组
  if (obj.constructor === Array) {
    copy = []
  } else {
    copy = {}
  }

  // 遍历：兼容数组
  for (let key in obj) {
    copy[key] = deepClone(obj[key])
  }

  return copy
}

const liLeiCopy = deepClone(liLei)
liLei.habits.splice(2, 1)
console.log(liLei, liLeiCopy)
